<?php

namespace App\Console\Commands;

use App\Model\Model;
use App\Model\Module;
use App\User;
use Illuminate\Console\Command;
use Spatie\Permission\Models\Role;

//use Spatie\Permission\Contracts\Permission;
//
class Permission extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:mj-permission';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '权限管理的命令artisan';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
     //权限设置都在这里完成
        //第一步：先判断我们要给权限的类是那些，主要看模块里有没有System这个m目录
        $models=glob('app/Http/Controllers/*');
        foreach ($models as $model){
            $dir=$model.'/System';
//            dump($dir);
            if (is_dir($dir)){
                //获得模块的名称
                $modelName=basename($model);
//                dump($modelName);
                //获得System下config文件的内容
                $config=include $dir.'/config.php';
                //获得System下perssion文件的内容
                $permissions=include $dir.'/permission.php';
//                dump($permission);
                //将当前模块的中英文明和模块所对应的权限存起来
                Module::firstOrNew(['name'=>$modelName])->fill(['cname'=>$config['app'],'permissions'=>$permissions])->save();
//                将每个模块的权限存到模块表里
                foreach ($permissions as $permission){
                    $name=$modelName.'-'.$permission['name'];
                    \Spatie\Permission\Models\Permission::firstOrNew(['name'=>$name])->fill(['cname'=>$permission['cname'],'model'=>$modelName])->save();
                }
            }
        }
        //给站长设置权限
//        找到站长
        $role=Role::where('name','webmaster')->first();
//        dump($role);
        //获得所有权限
        $permission=\Spatie\Permission\Models\Permission::pluck('name');
//        dump($permission);
        //给站长设置所有权限
        $role->syncPermissions($permission);
        //将站长角色分配给某个用户
        $user=User::find(1);
        $user->syncRoles('webmaster');
        //清楚一下权限的缓存
        app()['cache']->forget('spatie.permission.cache');
        $this->info('权限设置成功');
    }
}
